﻿/*
Copyright (c) 2012 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Windows.Forms;

namespace TeachMe.Application
{
    public class Suspender
    {
        public EventHandler<EventArgs> Suspended;
        public EventHandler<EventArgs> Resumed;
        
        private Timer _timer;

        public Suspender()
        {
            _timer = new Timer();
            _timer.Interval = 1000 * 60; // once per minute
            _timer.Enabled = true;
            _timer.Tick += delegate
            {
                if (Countdown != null)
                {
                    if (--Countdown == 0)
                    {
                        PausedCountdown = null;
                        Countdown = null;

                        Resume();
                    }   
                }
            };
        }

        public int? PausedCountdown { get; private set; }

        public int? Countdown { get; private set; }

        public bool IsSuspended { get; private set; }

        public bool IsSuspendedByInterval
        {
            get { return IsSuspended && Countdown > 0; }
        }

        public void Suspend()
        {
            IsSuspended = true;

            if (Countdown != null)
            {
                PausedCountdown = Countdown;
                Countdown = null;
            }

            RaiseSuspend();
        }

        public void Suspend(int minutes)
        {
            IsSuspended = true;

            Countdown = minutes;

            RaiseSuspend();
        }

        public void Resume()
        {
            if (PausedCountdown != null)
            {
                Countdown = PausedCountdown;
                PausedCountdown = null;

                return;
            }

            IsSuspended = false;

            RaiseResumed();
        }

        private void RaiseResumed()
        {
            EventHandler<EventArgs> handler = Suspended;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        private void RaiseSuspend()
        {
            EventHandler<EventArgs> handler = Suspended;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }
}
